<?php require_once 'conf.php'; ?>
<?php
require_once "services/budgetServices.php";

class CommonServices {

	public function getMonthName($month, $userid, $format){
		$dateFormat = "M Y";
		if ($format == "short"){
			$dateFormat = "M Y";
		} else if ($format == "long"){
			$dateFormat = "F Y";
		} else if ($format == "full"){
			$dateFormat = "Y-m-d";
		}

		$startDate = self::getStartDateOfBudget($month, $userid);

		return date($dateFormat, strtotime($startDate));
	}

	public function getEndOfWeek($budgetId, $weekNo){
		$format = 'Y-m-d';
		$budgetStartDate = self::getStartDateForBudget($budgetId);

		if (date('l', strtotime($budgetStartDate)) == "Sunday"){
			return $budgetStartDate;
		}

		$count  = 0;
		$curreWeekNo = 0;

		while ($curreWeekNo < $weekNo){
			do {
				$currentDate = date($format, strtotime('+'. $count .' day', strtotime($budgetStartDate)));
				$weekday = date('l', strtotime($currentDate));
				$count++;
			} while ($weekday != "Sunday");
			$curreWeekNo++;
		}

		return $currentDate;
	}

	public function getStartOfWeek($budgetId, $weekNo){
		$format = 'Y-m-d';
		$budgetStartDate = self::getStartDateForBudget($budgetId);

		if (date('l', strtotime($budgetStartDate)) == "Monday"){
			return $budgetStartDate;
		}

		if ($weekNo == 1){
			return $budgetStartDate;
		}

		$count  = 0;
		$curreWeekNo = 1;

		while ($curreWeekNo < $weekNo){
			do {
				$currentDate = date($format, strtotime('+'. $count .' day', strtotime($budgetStartDate)));
				$weekday = date('l', strtotime($currentDate));
				error_log($weekday);
				$count++;
			} while ($weekday != "Monday");
			$curreWeekNo++;
		}

		//error_log($currentDate);

		return $currentDate;
	}


	public function getSavingsAccountId(){
		$con = mysql_connect(GlobalConfig::db_host_name,GlobalConfig::db_username,GlobalConfig::db_password);
		mysql_select_db(GlobalConfig::db_name, $con);
		$query = "select id from account where type=1";
		error_log($query);

		$result = mysql_query($query);
		$id = -1;
		while ($row = mysql_fetch_array($result)){
			$id = $row["id"];
		}

		return $id;
	}

	public function getCashAccountId(){
		$con = mysql_connect(GlobalConfig::db_host_name,GlobalConfig::db_username,GlobalConfig::db_password);
		mysql_select_db(GlobalConfig::db_name, $con);
		$query = "select id from account where name='CASH2' limit 1";
		error_log($query);

		$result = mysql_query($query);
		$id = -1;
		while ($row = mysql_fetch_array($result)){
			$id = $row["id"];
		}

		return $id;
	}

	public function getSavingsDifference($userid){
		$budgetServices = new BudgetService;
		$savingsId = $budgetServices->getSavingsAccountId($userid);
		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$query = "select t.amount, t.accountId as accountId from transaction t, account a where t.accountId=a.id and a.userid=:userid and t.amount<> 0 and t.parentTransId=0 and t.reconciled is false order by date asc";
			$stmt = $con->prepare($query);
			$stmt->bindParam(':userid', $userid);

			$difference = 0;
			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					if ($row["accountId"] == $savingsId){
						$difference += $row["amount"];
					}
				}
			}

			if ($difference == ""){
				$difference =0;
			}
			return $difference;

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('017');
		}
	}

	public function getBalanceForAcccount($accountId){
		$con = mysql_connect(GlobalConfig::db_host_name,GlobalConfig::db_username,GlobalConfig::db_password);
		mysql_select_db(GlobalConfig::db_name, $con);
		$query = "select type from account where id=" . $accountId;
		error_log($query);
		$result = mysql_query($query) or die(mysql_error());
		$row = mysql_fetch_array($result);
		$accountType = $row["type"];

		error_log($accountType);

		if ($accountType == 5){
			return self::getBalanceForNormalAccount($accountId);
		} if ($accountType == 2){
			return self::getBalanceForNormalAccount($accountId);
		} else if ($accountType == 1){
			return self::getBalanceForSavingsAccount($accountId);
		} else {
			return self::getBalanceForNormalAccount($accountId);
		}
	}

	function getBalanceForSavingsAccount($accountId){
		$con = mysql_connect(GlobalConfig::db_host_name,GlobalConfig::db_username,GlobalConfig::db_password);
		mysql_select_db(GlobalConfig::db_name, $con);
		$query = "select s.id, s.budgetitemid, b.description, s.openingBalance from subaccount s, budgetitem b where s.budgetitemid=b.id and s.parentAccId=" . $accountId;
		error_log($query);
		$result = mysql_query($query) or die(mysql_error());
		$storedResults = array();
		$count = 0;
		while ($row = mysql_fetch_array($result)){
			$storedResults[$count] = $row;
			$count++;
		}

		$balance = 0;

		foreach ($storedResults as $value){

			$result1 = mysql_query("select sum(amount) as sum from transaction where budgetitemid=". $value["budgetitemid"] ." and categoryId=4 and accountId=". $accountId);
			$sum = mysql_fetch_array($result1);

			$balance += ($value["openingBalance"] + $sum["sum"]);
		}


		return $balance;
	}

	function getBalanceForNormalAccount($accountId){
		$con = mysql_connect(GlobalConfig::db_host_name,GlobalConfig::db_username,GlobalConfig::db_password);
		if (!$con)
		{
			die('Could not connect: ' . mysql_error());
		}

		mysql_select_db(GlobalConfig::db_name, $con);
		$query = "select openingBalance from account where id=" . $accountId;
		error_log($query);
		$result = mysql_query($query) or die(mysql_error());
		$row = mysql_fetch_array($result);
		$openingBalance = $row["openingBalance"];

		$totalBalance = $openingBalance;

		$query = "select amount from transaction where accountId = " . $accountId ." order by date";
		$result = mysql_query($query) or die(mysql_error());
		error_log($query);
		while($row = mysql_fetch_array($result))  {
			$totalBalance =  $totalBalance + $row['amount'];
		}

		return $totalBalance;
	}

	public function getIntValForMonth($monthStr){
		if ($monthStr == "January"){
			return 1;
		} else
		if ($monthStr == "February"){
			return 2;
		} else
		if ($monthStr == "March"){
			return 3;
		} else
		if ($monthStr == "April"){
			return 4;
		} else
		if ($monthStr == "May"){
			return 5;
		} else
		if ($monthStr == "June"){
			return 6;
		} else
		if ($monthStr == "July"){
			return 7;
		} else
		if ($monthStr == "August"){
			return 8;
		} else
		if ($monthStr == "September"){
			return 9;
		} else
		if ($monthStr == "October"){
			return 10;
		} else
		if ($monthStr == "November"){
			return 11;
		} else
		if ($monthStr == "December"){
			return 12;
		}
	}

	public function getThisMonthStartDate($userid){
		try {
			$startDate = $this->getEndOfMonthDayForUser($userid);

			$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
			mysql_select_db(GlobalConfig::db_name, $con);

			if (date("d") >= $startDate){
				$date = date("Y-m-d");
			} else {
				$date = date("Y-m-d", strtotime("-1 month"));
			}

			$date = substr_replace($date, $startDate, 8);

			error_log($date);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('005');
		}

		return $date;
	}

	/**
	 * Gets the budget start date for the specified month.
	 *
	 *$month - an int value specifying the month.
	 *
	 *e.g. 0 = current month.
	 *e.g. -1 = last month
	 */
	public function getStartDateOfBudget($month, $userid){
		try {
			$startDate = $this->getEndOfMonthDayForUser($userid);

			if (date("d") >= $startDate){
				$date = date("Y-m-d", strtotime($month." month"));
			} else {
				$date = date("Y-m-d", strtotime(($month-1)." month"));
			}

			$date = substr_replace($date, $startDate, 8);

			//error_log("THE DATE SHOULD BE ".$date);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('005');
		}

		return $date;
	}

	public function getBudgetUserId($budgetId){
		try{
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select userid from budget where id=:budgetid");
			$stmt->bindParam(':budgetid', $budgetId);

			$userid=-1;
			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$userid = $row['userid'];
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('017');
		}
		return $userid;
	}

	public function getStartDateForBudget($budgetId){
		$startDate = $this->getEndOfMonthDayForUser($this->getBudgetUserId($budgetId));

		$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
		mysql_select_db(GlobalConfig::db_name, $con);

		$query = "select * from budget where id=". $budgetId;
		$result1 = mysql_query($query);

		if ($row = mysql_fetch_array($result1)) {
			$monthString = $row['month'];
		}

		$monthArray =  split(" ", $monthString);

		$month = $monthArray[0];
		$year = $monthArray[1];

		$monthIntVal = self::getIntValForMonth($month);

		if (($monthIntVal-1) == 0){
			$month = 12;
			$year = $year-1;
		} else if (($monthIntVal-1) < 10){
			$month = "0". strval($monthIntVal-1);
		} else {
			$month = strval($monthIntVal-1);
		}

		mysql_close($con);
		return $year."-". $month ."-".$startDate;
	}


	public function getEndDateForBudget($budgetId){
		$startDate = $this->getEndOfMonthDayForUser($this->getBudgetUserId($budgetId));

		$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
		mysql_select_db(GlobalConfig::db_name, $con);

		$query = "select * from budget where id=". $budgetId;
		error_log($query);
		$result1 = mysql_query($query);

		if ($row = mysql_fetch_array($result1)) {
			$monthString = $row['month'];
		}

		$monthArray =  split(" ", $monthString);

		$month = $monthArray[0];
		$year = $monthArray[1];

		if ((self::getIntValForMonth($month)-1) < 9){
			$month = "0". strval(self::getIntValForMonth($month));
		} else {
			$month = strval(self::getIntValForMonth($month));
		}

		error_log("endDate: ".$year."-". $month ."-". ($startDate-1));

		mysql_close($con);

		return $year."-". $month ."-".($startDate-1);
	}

	/**
	 * Gets the budget end date for the specified month.
	 *
	 *$month - an int value specifying the month.
	 *
	 *e.g. 0 = current month.
	 *e.g. -1 = last month
	 */
	public function getEndDateOfBudget($month, $userid){
		try {
			$startDate = $this->getEndOfMonthDayForUser($userid);
			$fStartDate = date("Y-m-d", mktime(0, 0, 0, date("n"), $startDate, date("Y")));

			$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
			mysql_select_db(GlobalConfig::db_name, $con);

			if (date("d") >= $startDate){
				$date = date("Y-m-d", strtotime("-1 day", strtotime(($month+1)." month", strtotime($fStartDate))));
			} else {
				$date = date("Y-m-d", strtotime("-1 day", strtotime(($month)." month", strtotime($fStartDate))));
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('005');
		}

		return $date;
	}

	public function getEndOfMonthDayForUser($userid){
		try{
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select cvalue from config where ckey='firstdayofmonth' and userid=:userid");
			$stmt->bindParam(':userid', $userid);


			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$startDate = $row['cvalue'];
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('017');
		}
		return $startDate;
	}

	public function getCurrentBudgetId($userid){
		$budgetId = -1;
		try {
			$startDate = (int)$this->getEndOfMonthDayForUser($userid);

			$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
			mysql_select_db(GlobalConfig::db_name, $con);

			$currentDay = (int)date("j");
			$currentMonthYear = date("F Y");
			$lastday = strtotime("last day");
			$nextMonthYear = date("F Y", strtotime("+1 days", strtotime(date("Y-m-t 23:59:59"))));

			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select * from budget where month=:month and userid=:userid");
			$stmt->bindParam(':userid', $userid);

			if($currentDay>=$startDate){
				$stmt->bindParam(':month', $nextMonthYear);
			}else{
				$stmt->bindParam(':month', $currentMonthYear);
			}

			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$budgetId = $row['id'];
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('007');
		}
		return $budgetId;
	}


}
?>
